<?php

/**
 * Setting form.
 *
 * @package    berta-s
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class SettingFormCommons extends BaseSettingForm
{
	private $fieldGroups=array();

	private function initFieldGroups(){
	    foreach ($this->getFormFieldSchema() as $field){
	    	$groupName=$this->getFieldsGroup($field);
	    	if ($groupName!="" && !in_array($groupName, $this->fieldGroups)){
	    		$this->setFieldGroup($groupName);
	    	}
	    }
	}

	public function getFieldGroups(){
		if (empty($this->fieldGroups)){
			$this->initFieldGroups();
		}
		return $this->fieldGroups;
	}


	public function getFieldsGroup($field){
	    $name=$field->getName();
		return substr($field->getName(), 0, strpos($name, "."));
	}

	private function setFieldGroup($groupName, $options=array()){
		if ($groupName!=""){
			$this->fieldGroups[$groupName]=$options;
		}
	}

	// override, we should only save fields with non-default values
	protected function doUpdateObject($values){
		$defaults = $this->getDefaults();

		/* filter out items with default values */
		$valuesToSave=array();
		foreach ($values as $key => $value){
			if (!array_key_exists($key, $defaults) || $value!=$defaults[$key]){
				if (! (!array_key_exists($key, $defaults) && $value=="") ){
                    $fullValue=$this->getValue($key);
                    if ($fullValue instanceOf sfValidatedFile){
                        /** @var $fullValue sfValidatedFile **/
                        $value=PathHelper::getPublicPath($fullValue->getSavedName());
                    }
					$valuesToSave[$key]=$value;
				}
			}
		}
		parent::doUpdateObject($valuesToSave);
	}

	// symfony form default camelize doesnt like "." in field names
	protected function camelize($text){
		return preg_replace(array('#/(.?)#e', '/(^|_|-|\.)+(.)/e'), array("'::'.strtoupper('\\1')", "strtoupper('\\2')"), $text);
	}


}
